/**
 * @Author: Bobby
 * @Date: 2022-03-21 09:17:11
 * @LastEditTime: 2022-03-21 09:47:40
 * @LastEditors: Bobby
 * @Description:
 * @FilePath: \wms-v2\src\ve\eventTask\actions\form\formReset.js
 * @CIMC-V2
 */
import cloneDeep from 'lodash/cloneDeep'
import keys from 'lodash/keys'
import includes from 'lodash/includes'
//必须带done回调 执行完成调用 vm, action, done
export default function formReset({ vm, action, done }) {
  if (action.extension.formSelect.value.length > 0) {
    action.extension.formSelect.value.forEach((item) => {
      let self = vm.vuiComponents[item].self
      if (self.getInfo.type == 'uiCirculationForm') {
        setData(self.getInfo._dataList, self.getInfo.dataList)
      } else {
        if (self && self.getInfo.data) {
          let resetData = {}
          if (self.getInfo.data._formData) {
            resetData = cloneDeep(self.getInfo.data._formData)
          } else {
            resetData = cloneDeep(self.getInfo.data.formData)
            Object.keys(resetData).forEach((key) => (resetData[key] = ''))
          }
          // 先查找改变了的值
          const keysList = keys(resetData)
          let changeModelList = []
          keysList.forEach((keyItem) => {
            if (resetData[keyItem] !== self.getInfo.data.formData[keyItem]) {
              changeModelList.push(keyItem)
            }
          })
          self.getInfo.data.formData = resetData
          // 提交 dispatch 触发页面组件状态更新（ dataObj 为传递的数据对象，moduleObj 为目标组件对象
          if (!(process.env.VUE_APP_BuildProjectType === 'mobile' || vm.$store.state.diy.settings.mode == 'mobile')) {
            vm.$store.dispatch('pageModulesState/setPageModulesStatesByObj', {
              pageId: vm.$store.getters['preview/getNowPageId'],
              pageState: { dataObj: self.getInfo.data.formData, moduleObj: self.getInfo },
            })
          }

          // 触发改变了的组件的值改变事件
          const eachFunc = (obj) => {
            const modelVal = obj.extension?.model?.value
            // 查找组件的 model 值绑定在修改值对象中
            if (modelVal && includes(changeModelList, modelVal)) {
              // 触发组件的值改变事件
              vm.vuiComponents[obj._id]?.self?.onChange()
            }
            obj.pageModules &&
              obj.pageModules.forEach((item) => {
                eachFunc(item)
              })
            obj.list &&
              obj.list.forEach((item) => {
                eachFunc(item)
              })
          }
          eachFunc(self.getInfo)
        }
      }
    })
  }
  done(null, {})
}
function setData(oldData, newData) {
  oldData.forEach((row, index) => {
    for (const key in row.data.formData) {
      const element = row.data.formData[key]
      if (element) {
        newData[index].data.formData[key] = element
      }
    }
  })
}
